package open.tech.dawn.rest.common.log.factory;

import lombok.extern.slf4j.Slf4j;
import open.tech.dawn.core.util.SpringContextHolder;
import open.tech.dawn.rest.common.log.enums.LogType;
import open.tech.dawn.rest.module.system.mapper.SysLoginLogMapper;
import open.tech.dawn.rest.module.system.model.SysLoginLog;

import java.util.TimerTask;

/**
 * 日志操作任务创建工厂
 */
@Slf4j
public class LogTaskFactory {

    private static SysLoginLogMapper loginLogMapper = SpringContextHolder.getBean(SysLoginLogMapper.class);

    public static TimerTask loginLog(String userId, final String ip) {
        return new TimerTask() {
            @Override
            public void run() {
                try {
                    SysLoginLog loginLog = LogFactory.createLoginLog(LogType.LOGIN, userId, null, ip);
                    loginLogMapper.insert(loginLog);
                } catch (Exception e) {
                    log.error("创建登录日志异常!", e);
                }
            }
        };
    }

    public static TimerTask loginLog(final String username, final String msg, final String ip) {
        return new TimerTask() {
            @Override
            public void run() {
                SysLoginLog loginLog = LogFactory.createLoginLog(
                        LogType.LOGIN_FAIL, null, "账号:" + username + "," + msg, ip);
                try {
                    loginLogMapper.insert(loginLog);
                } catch (Exception e) {
                    log.error("创建登录失败异常!", e);
                }
            }
        };
    }

    public static TimerTask exitLog(String userId, final String ip) {
        return new TimerTask() {
            @Override
            public void run() {
                SysLoginLog loginLog = LogFactory.createLoginLog(LogType.EXIT, userId, null, ip);
                try {
                    loginLogMapper.insert(loginLog);
                } catch (Exception e) {
                    log.error("创建退出日志异常!", e);
                }
            }
        };
    }
}
